<template>
	<view class="leave-page">
		<!-- 自定義導航欄 -->
		<u-navbar
			title="请假申请"
			:border="false"
			:auto-back="true"
			:bg-color="'#FFFFFF'"
			:title-color="'#333333'"
			:title-size="36"
			:title-weight="'bold'"
			placeholder
		>
		</u-navbar>


		
		<!-- 排序和筛选区域 -->
		<view class="filter-section">
			<view class="filter-item" @click="showSortOptions()">
				<text class="filter-text">{{ currentSortMethod || '排序' }}</text>
				<text class="filter-arrow">▼</text>
			</view>
			<view class="filter-item" @click="openFilterModal()" :class="{ 'filter-active': hasFilterContent }">
				<text class="filter-text">筛选</text>
				<text class="filter-arrow">▼</text>
			</view>
		</view>
		
		<!-- 多选模式下的操作栏 - 固定在筛选区域下方 -->
		<view v-if="isMultiSelectMode" class="multi-select-bar">
			<view class="select-info">
				<text class="select-text">已选中{{ selectedItems.length }}条</text>
			</view>
			<view class="select-actions">
				<button 
					class="btn btn-primary" 
					@click="submitSelected"
				>
					提交流程
				</button>
				<button 
					class="btn btn-error" 
					@click="deleteSelected"
				>
					删除
				</button>
			</view>
		</view>
		
		<!-- 筛选模态框 -->
		<u-popup 
			:show="showFilterPopup" 
			@close="closeFilterModal"
			mode="top"
			safeAreaInsetTop
		>
			<view class="filter-modal">
				<view class="filter-modal-header">
					<text class="filter-modal-title">筛选</text>
				</view>
				
				<view class="filter-modal-content">
					<!-- 申请日期 -->
					<view class="filter-modal-item">
						<text class="filter-modal-label">申请日期</text>
						<view class="filter-modal-input" @click="openDatePicker">
							<text class="filter-modal-text">
								{{ filterData.applyDate || '请选择日期' }}
							</text>
							<text class="filter-modal-arrow">›</text>
						</view>
					</view>
					
					<!-- 请假状态 -->
					<view class="filter-modal-item">
						<text class="filter-modal-label">请假状态</text>
						<view class="filter-modal-input" @click="openStatusPicker">
							<text class="filter-modal-text">
								{{ filterData.status === '1' ? '暂存' 
									: filterData.status === '2' ? '提交'
									: filterData.status === '4' ? '审核'
									: filterData.status === '5' ? '销假'
									: '请选择状态' }}
							</text>
							<text class="filter-modal-arrow">›</text>
						</view>
					</view>
				</view>
				
				<view class="filter-modal-actions">
					<button class="filter-modal-btn filter-reset-btn" @click="resetFilter">重置</button>
					<button class="filter-modal-btn filter-apply-btn" @click="applyFilterAndClose">确定</button>
				</view>
			</view>
		</u-popup>
		
		<!-- 请假申请列表 - 滚动区域 -->
		<scroll-view class="leave-list" scroll-y="true">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 数据列表 -->
			<view v-else>
				<u-swipe-action>
					<u-swipe-action-item 
						v-for="(item, index) in leaveList" 
						:key="index"
						:options="getSwipeOptions(item)"
						@click="handleSwipeClick"
						:name="index"
					>
						<view class="leave-item" :class="{ 'selected': selectedItems.includes(item.id) }">
							<!-- 多选模式下的选择框 -->
							<view 
								v-if="isMultiSelectMode && (item.status === 'pending')" 
								class="select-checkbox"
								:class="{ 'selected': selectedItems.includes(item.id) }"
								@click.stop="toggleSelect(item.id)"
							>
								<text class="checkbox-icon">{{ selectedItems.includes(item.id) ? '✓' : '○' }}</text>
							</view>
							
							<view class="leave-content" @click="viewDetail(item)">
								<view class="item-header">
									<view class="item-title">
										<text class="title-text">{{ item.leaveType }}</text>
										<text class="status-tag" :class="item.status">{{ item.statusText }}</text>
									</view>
									<view class="item-amount">
										<text class="amount-text">{{ item.duration }}小时</text>
									</view>
								</view>
								
								<view class="item-info">
									<view class="info-row">
										<text class="info-label">开始时间：</text>
										<text class="info-value">{{ item.startTime }}</text>
									</view>
									<view class="info-row">
										<text class="info-label">结束时间：</text>
										<text class="info-value">{{ item.endTime }}</text>
									</view>
									<view class="info-row">
										<text class="info-label">请假事由：</text>
										<text class="info-value">{{ item.reason || '无' }}</text>
									</view>
								</view>
							</view>
						</view>
					</u-swipe-action-item>
				</u-swipe-action>
				
				<!-- 空状态 -->
				<view v-if="leaveList.length === 0 && !loading" class="empty-state">
					<view class="empty-illustration">
						<img class="img" src="@/static/icon/empty.png" />
					</view>
					<text class="empty-text">暂无请假申请记录</text>
					<view class="empty-actions">
						<view class="action-btn refresh-btn" @click="refreshData">
							<text class="btn-text">刷新重试</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
	
	<!-- 日期选择器弹窗 -->
	<u-datetime-picker
		:show="showDatePicker"
		mode="date"
		v-model="currentDate"
		@confirm="onDateConfirm"
		@cancel="showDatePicker = false"
		:custom-style="{ 
			confirmColor: '#FF6B35',
			cancelColor: '#666666'
		}"
		:min-date="new Date('2020-01-01').getTime()"
		:max-date="new Date('2030-12-31').getTime()"
		:close-on-click-overlay="false"
		:show-toolbar="true"
		:title="'选择日期'"
		:z-index="1000"
	/>
	
	<!-- 固定操作按钮 -->
	<view class="fixed-actions-container">
		<button class="fab fab-primary" @click="goToAdd">
			<text class="fab-icon">+</text>
		</button>
		<button class="fab fab-secondary" @click="toggleMultiSelectMode">
			<text class="fab-icon">☑</text>
		</button>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { leaveApi } from '@/api/api-helper.js' // TODO: 需要创建请假申请相关的API
import { onShow } from '@dcloudio/uni-app'
import { userStore } from '@/stores/userStore'

// 响应式数据
const loading = ref(false)
const isMultiSelectMode = ref(false)
const selectedItems = ref<string[]>([])
const currentSortMethod = ref('')
const showFilterPopup = ref(false)
const showDatePicker = ref(false)
const currentDate = ref(new Date().getTime())

// 筛选数据
const filterData = ref({
	applyDate: '', // 申请日期
	status: '' // 请假状态
})

// 请假申请列表数据
const leaveList = ref([])

// 模拟数据
const mockData = [
	{
		id: '1',
		leaveType: '事假',
		startTime: '2025-07-18 21:15',
		endTime: '2025-07-18 23:15',
		duration: '2',
		reason: '个人事务',
		status: 'pending',
		statusText: '待审批',
		billStatus: '0'
	},
	{
		id: '2',
		leaveType: '病假',
		startTime: '2025-07-19 09:00',
		endTime: '2025-07-19 18:00',
		duration: '9',
		reason: '身体不适',
		status: 'submitted',
		statusText: '已提交',
		billStatus: '2'
	},
	{
		id: '3',
		leaveType: '调休假',
		startTime: '2025-07-20 09:00',
		endTime: '2025-07-20 18:00',
		duration: '9',
		reason: '调休补班',
		status: 'approved',
		statusText: '已批准',
		billStatus: '4'
	}
]

// 获取请假申请列表
const getLeaveList = async () => {
	loading.value = true
	try {
		const openId = userStore.getOpenId()
		if (!openId) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}

		const params: any = {
			openId: openId,
			currentPage: 1,
			pageSize: 10000
		}

		// 添加筛选条件
		if (filterData.value.applyDate) {
			params.bizDate = filterData.value.applyDate
		}
		if (filterData.value.status) {
			params.billStatus = filterData.value.status
		}
		
		// 添加排序参数
		if (currentSortMethod.value) {
			// 根据当前排序标签转换为接口参数
			if (currentSortMethod.value.includes('请假类型')) {
				params.sort = 'leaveTypeName'
			} else if (currentSortMethod.value.includes('开始时间')) {
				params.sort = 'startTime'
			} else if (currentSortMethod.value.includes('结束时间')) {
				params.sort = 'endTime'
			} else if (currentSortMethod.value.includes('时长')) {
				params.sort = 'duration'
			}
			
			// 添加排序方向
			if (currentSortMethod.value.includes('降序')) {
				params.order = 'desc'
			} else if (currentSortMethod.value.includes('升序')) {
				params.order = 'asc'
			}
		}

		// 调用请假申请API接口
		const response = await leaveApi.getLeaveList(params)
		
		console.log('请假申请API响应:', response)
		
		if (response && response.code === 200) {
			// 使用API返回的数据
			const responseData = response.data
			const list = responseData.list || []
			
			// 根据接口文档映射数据字段
			let processedList = list.map(item => ({
				id: item.id,
				leaveType: item.leaveTypeName || '请假申请', // 接口返回 leaveTypeName
				startTime: item.startTime || '未知',
				endTime: item.endTime || '未知',
				duration: item.durationHours || '0',
				reason: item.description || '无', // 接口返回 description
				status: getStatusMapping(item.billStatus), // 转换状态值
				statusText: item.billStatusName || '未知状态', // 接口返回 billStatusName
				billStatus: item.billStatus || '', // 保存原始状态值
				// 新增接口返回的原始数据
				bizDate: item.bizDate || '', // 申请日期
				leaveTypeId: item.leaveTypeId || '' // 请假类型ID
			}))

			leaveList.value = processedList
			console.log('处理后的请假申请列表数据:', leaveList.value)
		} else {
			uni.showToast({
				title: response?.msg || '获取数据失败',
				icon: 'none'
			})
		}
		
	} catch (error) {
		console.error('获取请假申请列表失败:', error)
		uni.showToast({
			title: '网络错误',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 获取费用项目文字
const getExpenseItemText = (borrowItemVOList: any[]) => {
	if (!borrowItemVOList || borrowItemVOList.length === 0) {
		return '--'
	}
	
	// 如果有多个费用项目，用逗号分隔
	const items = borrowItemVOList.map(item => item.expenseName || item.expenseId || '未知项目')
	return items.join(', ')
}

// 状态值映射
const getStatusMapping = (billStatus: string) => {
	switch (billStatus) {
		case '1': return 'pending'    // 暂存
		case '2': return 'submitted'  // 提交
		case '4': return 'approved'   // 审核
		case '5': return 'cancelled'  // 销假
		default: return 'pending'
	}
}

// 获取右滑动选项
const getSwipeOptions = (item: any) => {
	const options = []
	
	// 根据状态显示不同的按钮
	if (item.status === 'pending') {
		options.push({
			text: '提交流程',
			style: {
				backgroundColor: '#FF6B35',
				color: '#FFFFFF'
			}
		})
	}
	
	// 只有暂存状态的项目可以删除
	if (item.status === 'pending') {
		options.push({
			text: '删除',
			style: {
				backgroundColor: '#FF4757',
				color: '#FFFFFF'
			}
		})
	}
	
	return options
}

// 处理右滑动按钮点击
const handleSwipeClick = (e: any) => {
	const { name, index } = e
	const item = leaveList.value[name]
	const option = getSwipeOptions(item)[index]
	
	if (option.text === '提交流程') {
		submitProcess(item)
	} else if (option.text === '删除') {
		deleteItem(item)
	}
}







const showViewOptions = () => {
	uni.showActionSheet({
		itemList: ['查看全部', '查看待审批', '查看已批准', '查看已拒绝'],
		success: (res) => {
			console.log('选择了:', res.tapIndex)
			// TODO: 实现不同的查看模式
		}
	})
}

// 方法
const showMoreOptions = () => {
	uni.showActionSheet({
		itemList: ['刷新', '导出', '设置'],
		success: (res) => {
			console.log('选择了:', res.tapIndex)
		}
	})
}

const showSearch = () => {
	uni.showToast({
		title: '搜索功能',
		icon: 'none'
	})
}

// 显示排序选项弹窗（包含清除排序）
const showSortOptions = () => {
	uni.showActionSheet({
		itemList: [
			'请假类型降序',
			'请假开始时间降序',
			'请假结束时间降序',
			'请假时长降序',
			'清除排序',
		],
		success: (res) => {
			if (res.tapIndex === 8) {
				// 清除排序
				clearSort()
				return
			}
			
			const sortOptions = [
				{ key: 'leaveTypeName-desc', label: '请假类型降序', desc: '请假类型降序' },
				{ key: 'leaveTypeName-asc', label: '请假类型升序', desc: '请假类型升序' },
				{ key: 'startTime-desc', label: '请假开始时间降序', desc: '请假开始时间降序' },
				{ key: 'startTime-asc', label: '请假开始时间升序', desc: '请假开始时间升序' },
				{ key: 'endTime-desc', label: '请假结束时间降序', desc: '请假结束时间降序' },
				{ key: 'endTime-asc', label: '请假结束时间升序', desc: '请假结束时间升序' },
				{ key: 'duration-desc', label: '请假时长降序', desc: '请假时长降序' },
				{ key: 'duration-asc', label: '请假时长升序', desc: '请假时长升序' }
			]
			
			const selectedOption = sortOptions[res.tapIndex]
			if (selectedOption) {
				// 直接执行排序，不需要二次确认
				applySort(selectedOption.key)
			}
		}
	})
}

// 应用排序
const applySort = async (sortMethod: string) => {
	let sortLabel = ''
	
	// 根据排序方式设置排序标签
	switch (sortMethod) {
		case 'leaveTypeName-desc':
			sortLabel = '请假类型降序'
			break
		case 'leaveTypeName-asc':
			sortLabel = '请假类型升序'
			break
		case 'startTime-desc':
			sortLabel = '请假开始时间降序'
			break
		case 'startTime-asc':
			sortLabel = '请假开始时间升序'
			break
		case 'endTime-desc':
			sortLabel = '请假结束时间降序'
			break
		case 'endTime-asc':
			sortLabel = '请假结束时间升序'
			break
		case 'duration-desc':
			sortLabel = '请假时长降序'
			break
		case 'duration-asc':
			sortLabel = '请假时长升序'
			break
	}
	
	// 设置排序标签
	currentSortMethod.value = sortLabel
	
	// 调用接口重新获取数据，传递排序参数
	await getLeaveList()
}

// 清除排序
const clearSort = async () => {
	// 清除排序标签
	currentSortMethod.value = ''
	
	// 调用接口重新获取数据，不传递排序参数
	await getLeaveList()
}

// 显示筛选选项
const openFilterModal = () => {
	console.log('点击筛选按钮，准备打开筛选模态框')
	console.log('当前 showFilterPopup 值:', showFilterPopup.value)
	showFilterPopup.value = true
	console.log('设置 showFilterPopup 为 true 后的值:', showFilterPopup.value)
}

const closeFilterModal = () => {
	showFilterPopup.value = false
}

// 应用筛选
const applyFilterAndClose = async () => {
	// 调用接口重新获取数据
	await getLeaveList()
	
	// 关闭筛选模态框
	showFilterPopup.value = false
}

// 重置筛选
const resetFilter = async () => {
	// 重置筛选条件
	filterData.value = {
		applyDate: '',
		status: ''
	}
	
	// 重置日期选择器的默认值为当前日期
	currentDate.value = new Date().getTime()
	
	// 调用接口重新获取数据
	await getLeaveList()
	
	// 关闭筛选模态框
	showFilterPopup.value = false
}

const toggleMultiSelectMode = () => {
	isMultiSelectMode.value = !isMultiSelectMode.value
	if (!isMultiSelectMode.value) {
		selectedItems.value = []
	}
}

const toggleSelect = (id: string) => {
	// 找到对应的项目
	const item = leaveList.value.find(item => item.id === id)
	if (!item) return
	
	// "提交"、"审核"和"销假"状态的项目不支持勾选
	if (item.status === 'submitted' || item.status === 'approved' || item.status === 'cancelled') {
		uni.showToast({
			title: '该状态不支持操作',
			icon: 'none'
		})
		return
	}
	
	const index = selectedItems.value.indexOf(id)
	if (index > -1) {
		selectedItems.value.splice(index, 1)
	} else {
		selectedItems.value.push(id)
	}
}

const submitProcess = async (item: any) => {
	uni.showModal({
		title: '确认提交',
		content: `确定要提交流程吗？`,
		success: async (res) => {
			if (res.confirm) {
				try {
					uni.showLoading({
						title: '提交中...',
						mask: true
					})
					
					const openId = userStore.getOpenId()
					if (!openId) {
						uni.hideLoading()
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						return
					}
					
					const response = await leaveApi.batchSubmit({
						openId: openId,
						ids: [item.id]
					})
					
					uni.hideLoading()
					
					if (response.code === 200) {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						// 重新获取数据
						await getLeaveList()
					} else {
						uni.showToast({
							title: response.msg || '提交失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('提交流程失败:', error)
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
				}
			}
		}
	})
}

const deleteItem = async (item: any) => {
	uni.showModal({
		title: '确认删除',
		content: `确定要删除这条请假申请记录吗？`,
		success: async (res) => {
			if (res.confirm) {
				try {
					uni.showLoading({
						title: '删除中...',
						mask: true
					})
					
					const openId = userStore.getOpenId()
					if (!openId) {
						uni.hideLoading()
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						})
						return
					}
					
							const response = await leaveApi.batchRemoveLeave({
			openId: openId,
			ids: [item.id]
		})
					
					uni.hideLoading()
					
					if (response.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
						// 重新获取数据
						await getLeaveList()
					} else {
						uni.showToast({
							title: response.msg || '删除失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('删除失败:', error)
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 批量提交
const submitSelected = async () => {
	if (selectedItems.value.length === 0) {
		uni.showToast({
			title: '请选择要提交的项目',
			icon: 'none'
		})
		return
	}
	
	uni.showModal({
		title: '确认提交',
		content: `确定要提交选中的${selectedItems.value.length}条记录吗？`,
		success: async (res) => {
			if (res.confirm) {
				try {
					uni.showLoading({
						title: '提交中...',
						mask: true
					})
					
					const openId = userStore.getOpenId()
					if (!openId) {
						uni.hideLoading()
						uni.showToast({
							title: '請先登錄',
							icon: 'none'
						})
						return
					}
					
					const response = await leaveApi.batchSubmit({
						openId: openId,
						ids: selectedItems.value
					})
					
					uni.hideLoading()
					
					if (response.code === 200) {
						uni.showToast({
							title: '批量提交成功',
							icon: 'success'
						})
						// 清空选中项目
						selectedItems.value = []
						// 退出多选模式
						isMultiSelectMode.value = false
						// 重新获取数据
						await getLeaveList()
					} else {
						uni.showToast({
							title: response.msg || '批量提交失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('批量提交失败:', error)
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 批量删除
const deleteSelected = async () => {
	if (selectedItems.value.length === 0) {
		uni.showToast({
			title: '请选择要删除的项目',
			icon: 'none'
		})
		return
	}
	
	uni.showModal({
		title: '确认删除',
		content: `确定要删除选中的${selectedItems.value.length}条记录吗？此操作不可恢复！`,
		success: async (res) => {
			if (res.confirm) {
				try {
					uni.showLoading({
						title: '删除中...',
						mask: true
					})
					
					const openId = userStore.getOpenId()
					if (!openId) {
						uni.hideLoading()
						uni.showToast({
							title: '請先登錄',
							icon: 'none'
						})
						return
					}
					
							const response = await leaveApi.batchRemoveLeave({
			openId: openId,
			ids: selectedItems.value
		})
					
					uni.hideLoading()
					
					if (response.code === 200) {
						uni.showToast({
							title: '批量删除成功',
							icon: 'success'
						})
						// 清空选中项目
						selectedItems.value = []
						// 退出多选模式
						isMultiSelectMode.value = false
						// 重新获取数据
						await getLeaveList()
					} else {
						uni.showToast({
							title: response.msg || '批量删除失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('批量删除失败:', error)
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
				}
			}
		}
	})
}

const goToAdd = () => {
	uni.navigateTo({
		url: '/pages/leave/add'
	})
}

const goBack = () => {
	uni.navigateBack()
}

const viewDetail = (item: any) => {
	// 传递状态信息到详情页
	const status = item.status // 前端状态值：pending, submitted, approved
	const billStatus = item.billStatus || '' // 后端状态值：0, 2, 4
	const statusText = item.statusText || '' // 状态文字：开立, 提交, 生效
	
	uni.navigateTo({
		url: `/pages/leave/detail?id=${item.id}&status=${status}&billStatus=${billStatus}&statusText=${encodeURIComponent(statusText)}`
	})
}

const getStatusClass = (status: string) => {
	switch (status) {
		case '生效':
			return 'status-active'
		case '提交':
			return 'status-pending'
		default:
			return 'status-default'
	}
}

// 显示日期选择器
const openDatePicker = () => {
	console.log('打开日期选择器')
	console.log('当前 currentDate:', currentDate.value)
	console.log('当前 filterData:', filterData.value)
	
	// 尝试使用 u-datetime-picker，如果失败则使用原生选择器
	try {
		showDatePicker.value = true
	} catch (error) {
		console.error('u-datetime-picker 打开失败，使用原生选择器:', error)
		openNativeDatePicker()
	}
}

// 备用：使用原生日期选择器
const openNativeDatePicker = () => {
	// 使用 uni-app 原生的日期选择器
	uni.showDatePicker({
		mode: 'date',
		value: new Date().toISOString().split('T')[0],
		success: (res) => {
			console.log('原生日期选择器结果:', res)
			if (res.value) {
				const dateStr = res.value
				
				// 如果还没有选择日期，则设置为日期
				if (!filterData.value.applyDate) {
					filterData.value.applyDate = dateStr
					uni.showToast({
						title: '已选择日期',
						icon: 'none'
					})
				}
			}
		},
		fail: (error) => {
			console.error('原生日期选择器失败:', error)
			uni.showToast({
				title: '日期选择失败，请重试',
				icon: 'none'
			})
		}
	})
}

// 日期选择确认
const onDateConfirm = (e: any) => {
	console.log('日期选择确认事件:', e)
	
	// 根据调试输出，e 的格式是 {value: "", mode: "date"}
	// 当 value 为空字符串时，表示用户没有选择日期
	if (!e || !e.value || e.value === '') {
		console.log('用户未选择日期或日期值为空')
		uni.showToast({
			title: '请选择一个日期',
			icon: 'none'
		})
		showDatePicker.value = false
		return
	}
	
	try {
		// 尝试解析日期值
		let selectedDate: Date
		
		if (typeof e.value === 'string' && e.value.length > 0) {
			// 如果是字符串格式，直接使用
			selectedDate = new Date(e.value)
		} else if (typeof e.value === 'number') {
			// 如果是时间戳
			selectedDate = new Date(e.value)
		} else if (Array.isArray(e.value)) {
			// 如果是数组格式，取第一个值
			selectedDate = new Date(e.value[0])
		} else {
			// 其他情况，尝试直接使用
			selectedDate = new Date(e.value)
		}
		
		// 验证日期是否有效
		if (isNaN(selectedDate.getTime())) {
			throw new Error('无效的日期值')
		}
		
		// 使用本地时间格式化，避免时区偏移问题
		const year = selectedDate.getFullYear()
		const month = String(selectedDate.getMonth() + 1).padStart(2, '0')
		const day = String(selectedDate.getDate()).padStart(2, '0')
		const dateStr = `${year}-${month}-${day}`
		console.log('选择的日期:', dateStr)
		
		// 设置日期到筛选条件
		filterData.value.applyDate = dateStr
		
		// 注意：使用 v-model 后，currentDate 会自动更新，不需要手动设置
		console.log('currentDate 已自动更新为:', currentDate.value)
		
		// 移除 toast 提醒，让日期选择更加静默
		
	} catch (error) {
		console.error('日期处理错误:', error, e)
		uni.showToast({
			title: '日期选择错误，请重试',
			icon: 'none'
		})
	}
	
	showDatePicker.value = false
}

// 显示状态选择器
const openStatusPicker = () => {
	uni.showActionSheet({
		itemList: ['暂存', '提交', '审核', '销假', '全部状态'],
		success: (res) => {
			console.log('状态选择结果:', res)
			const statusMap = {
				0: '1',    // 暂存
				1: '2',    // 提交
				2: '4',    // 审核
				3: '5',    // 销假
				4: ''      // 全部状态
			}
			const selectedStatus = statusMap[res.tapIndex]
			console.log('选择的状态值:', selectedStatus)
			filterData.value.status = selectedStatus
			console.log('设置后的filterData.status:', filterData.value.status)
		}
	})
}

// 计算是否有筛选内容
const hasFilterContent = computed(() => {
	return filterData.value.applyDate || filterData.value.status
})

onShow(() => {
	console.log('请假申请页面加载完成')
	console.log('showFilterPopup 初始值:', showFilterPopup.value)
	// 调用接口获取数据
	getLeaveList()
})

// 刷新数据
const refreshData = () => {
	console.log('点击刷新按钮，重新获取数据')
	getLeaveList()
}
</script>

<style lang="scss" scoped>
.leave-page {
	background-color: #F5F5F5;
	position: relative; /* 添加相對定位 */
	overflow-x: hidden; /* 防止水平滾動影響固定按鈕 */
	:deep(.u-swipe-action-item){
		overflow: unset;
	}
}

/* 筛选区域 */
.filter-section {
	background-color: #FFFFFF;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #F0F0F0;
	display: flex;
	align-items: center;
	
	.filter-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
		margin-right: 40rpx;
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		background-color: #F8F8F8;
		cursor: pointer;
		transition: all 0.3s ease;
		pointer-events: auto; /* 确保点击事件能够被触发 */
		
		&:hover {
			background-color: #F0F0F0;
		}
		
		&:active {
			background-color: #E8E8E8;
		}
		
		&.filter-active {
			background-color: var(--u-primary, #FF6B35);
			color: #FFFFFF;
			
			.filter-text {
				color: #FFFFFF;
			}
			
			.filter-arrow {
				color: #FFFFFF;
			}
		}
		
		.filter-text {
			font-size: 28rpx;
			color: #333333;
			font-weight: 500;
		}
		
		.filter-arrow {
			font-size: 24rpx;
			color: #999999;
			transition: transform 0.3s ease;
			
			&.filter-arrow-up {
				transform: rotate(180deg);
			}
		}
	}
}

/* 筛选条件区域 */
.filter-conditions {
	background-color: #FFFFFF;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #F0F0F0;
}

.filter-condition-item {
	margin-bottom: 25rpx;
}

.condition-label {
	display: block;
	font-size: 28rpx;
	color: #666666;
	margin-bottom: 10rpx;
}

.condition-input {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15rpx 20rpx;
	border: 1rpx solid #E0E0E0;
	border-radius: 10rpx;
	background-color: #F8F8F8;
	cursor: pointer;
	transition: all 0.3s ease;
	
	&:hover {
		background-color: #F0F0F0;
		border-color: #FF6B35;
	}
}

.condition-text {
	font-size: 28rpx;
	color: #333333;
	flex: 1;
}

.condition-arrow {
	font-size: 24rpx;
	color: #999999;
}

/* 筛选操作按钮 */
.filter-actions-bar {
	background-color: #FFFFFF;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #F0F0F0;
	display: flex;
	justify-content: space-between;
	gap: 20rpx;
}

.filter-action-btn {
	flex: 1;
	padding: 20rpx 0;
	border-radius: 20rpx;
	border: none;
	font-size: 28rpx;
	font-weight: bold;
	cursor: pointer;
	transition: all 0.3s ease;
	
	&.filter-reset-btn {
		background-color: #F0F0F0;
		color: #333333;
		
		&:hover {
			background-color: #E0E0E0;
		}
	}
	
	&.filter-search-btn {
		background-color: #FF6B35;
		color: #FFFFFF;
		
		&:hover {
			background-color: #E55A2B;
		}
	}
}

/* 多选模式操作栏 */
.multi-select-bar {
	background-color: #FFFFFF;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #F0F0F0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	position: sticky; /* 粘性定位 */
	top: 0; /* 固定在頂部 */
	z-index: 10; /* 確保在其他元素之上 */
	
	.select-info {
		.select-text {
			font-size: 28rpx;
			color: #666666;
		}
	}
	
	.select-actions {
		display: flex;
		gap: 10rpx;
	}
}

/* 按钮样式 */
.btn {
	padding: 2rpx 12rpx; /* 改小 padding */
	border-radius: 16rpx; /* 改小圓角 */
	border: none;
	font-size: 22rpx; /* 改小字體 */
	cursor: pointer;
	transition: all 0.3s ease;

	&.btn-primary {
		background-color: #FF6B35;
		color: #FFFFFF;
	}

	&.btn-error {
		background-color: #FF4757;
		color: #FFFFFF;
	}
}

.loading-text {
	font-size: 22rpx;
}

/* 请假申请列表 */
.leave-list {
	padding: 20rpx;
	height: calc(100vh - 200rpx); /* 调整滚动区域高度，减少底部空白 */
	position: relative; /* 添加相對定位 */
	z-index: 1; /* 设置较低的 z-index */
}

/* 右滑动组件样式 */
:deep(.u-swipe-action) {
	position: relative;
	z-index: 1;
}

:deep(.u-swipe-action-item) {
	position: relative;
	z-index: 1;
	margin-right: 40rpx !important; /* 修復右側邊距問題 */
}

.leave-item {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	display: flex; /* 使用 flex 布局 */
	align-items: center; /* 垂直居中 */
	
			&.selected {
			border: 2rpx solid var(--u-primary); /* 选中状态的边框 */
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}
}

.select-checkbox {
	width: 40rpx; /* 选择框的宽度 */
	height: 40rpx; /* 选择框的高度 */
	border-radius: 50%; /* 圆形选择框 */
	background-color: #CCCCCC; /* 未选中状态用灰色背景 */
	color: #FFFFFF; /* 选择框文字颜色 */
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx; /* 與內容的間距 */
	flex-shrink: 0; /* 防止縮放 */
	cursor: pointer; /* 手型光標 */
	transition: all 0.3s ease; /* 添加過渡動畫 */
	
	.checkbox-icon {
		font-size: 24rpx; /* 选择框图标大小 */
		font-weight: bold; /* 加粗 */
		line-height: 1; /* 行高 */
	}
	
	/* 选中状态的样式 */
	&.selected {
		background-color: var(--u-primary); /* 选中状态用橙色背景 */
	}
}

.leave-content {
	flex: 1; /* 內容區域佔據剩餘空間 */
}

.item-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 20rpx;
}

.item-title {
	flex: 1;
	display: flex;
	align-items: center; /* 改為水平對齊 */
	gap: 15rpx; /* 标题和状态标签之间的间距 */
}

.title-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.status-tag {
	display: inline-block;
	padding: 4rpx 12rpx;
	border-radius: 20rpx;
	font-size: 22rpx; /* 稍微調小一點 */
	color: #FFFFFF;
	flex-shrink: 0; /* 防止被壓縮 */
	
	&.pending {
		background-color: #FF9500;
	}
	
	&.submitted {
		background-color: #007AFF;
	}
	
	&.approved {
		background-color: #34C759;
	}
	
	&.cancelled {
		background-color: #FF3B30;
	}
	
	&.rejected {
		background-color: #FF3B30;
	}
}

.item-amount {
	text-align: right;
}

.amount-text {
	font-size: 36rpx;
	font-weight: bold;
	color: #FF6B35;
}

.item-info {
	.info-row {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.info-label {
			font-size: 28rpx;
			color: #666666;
			width: 140rpx;
			flex-shrink: 0;
		}
		
		.info-value {
			font-size: 28rpx;
			color: #333333;
			flex: 1;
		}
	}
}

/* 状态样式 */
.status {
	&.status-active {
		color: #52C41A;
	}
	&.status-pending {
		color: #FAAD14;
	}
	&.status-default {
		color: #666666;
	}
}




/* 固定操作按鈕 - 完全獨立的容器 */
.fixed-actions-container {
	position: fixed !important;
	right: 30rpx !important;
	bottom: 120rpx !important;
	display: flex !important;
	flex-direction: column !important;
	gap: 20rpx !important;
	z-index: 100 !important; /* 降低 z-index，确保日期选择器在最上层 */
	pointer-events: auto !important;
}

.fab {
	width: 100rpx !important;
	height: 100rpx !important;
	border-radius: 50% !important;
	border: none !important;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15) !important;
	cursor: pointer !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
	transition: all 0.3s ease !important;
	
	&.fab-primary {
		background-color: var(--u-primary) !important;
		color: #FFFFFF !important;
		
		&:hover {
			background-color: var(--u-primary-dark) !important;
			transform: scale(1.05) !important;
		}
	}
	
	&.fab-secondary {
		background-color: #FFFFFF !important;
		color: var(--u-primary) !important;
		border: 2rpx solid var(--u-primary) !important;
		
		&:hover {
			background-color: var(--u-primary) !important;
			color: #FFFFFF !important;
			transform: scale(1.05) !important;
		}
	}
	
	.fab-icon {
		font-size: 40rpx !important;
		font-weight: bold !important;
	}
}

/* 筛选模态框样式 */
.filter-modal {
	padding: 25rpx;
	display: flex;
	flex-direction: column;
	gap: 18rpx;
}

.filter-modal-header {
	text-align: center;
	padding-bottom: 12rpx;
	border-bottom: 1rpx solid #F0F0F0;
}

.filter-modal-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #333333;
}

.filter-modal-content {
	display: flex;
	flex-direction: column;
	gap: 18rpx;
}

.filter-modal-item {
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.filter-modal-label {
	font-size: 25rpx;
	color: #666666;
	min-width: 90rpx;
}

.filter-modal-input {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 10rpx 14rpx;
	border: 1rpx solid #E8E8E8;
	border-radius: 6rpx;
	background-color: #FFFFFF;
	cursor: pointer;
	transition: all 0.2s ease;
	
	&:hover {
		background-color: #FAFAFA;
		border-color: #FF6B35;
	}
}

.filter-modal-text {
	font-size: 25rpx;
	color: #333333;
	flex: 1;
}

.filter-modal-arrow {
	font-size: 18rpx;
	color: #999999;
}

.filter-modal-actions {
	display: flex;
	justify-content: space-between;
	gap: 12rpx;
	padding-top: 12rpx;
	border-top: 1rpx solid #F0F0F0;
}

.filter-modal-btn {
	flex: 1;
	padding: 12rpx 0;
	border-radius: 6rpx;
	border: none;
	font-size: 25rpx;
	font-weight: 500;
	cursor: pointer;
	transition: all 0.2s ease;
	
	&.filter-reset-btn {
		background-color: #F5F5F5;
		color: #666666;
		
		&:hover {
			background-color: #EBEBEB;
		}
	}
	
	&.filter-apply-btn {
		background-color: #FF6B35;
		color: #FFFFFF;
		
		&:hover {
			background-color: #E55A2B;
		}
	}
}

/* 日期选择器样式 */
:deep(.u-datetime-picker) {
	z-index: 1000 !important;
}

:deep(.u-popup) {
	z-index: 1000 !important;
}

:deep(.u-overlay) {
	z-index: 999 !important;
}

/* 加载状态样式 */
.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 50rpx 0;
}

.loading-spinner {
	width: 80rpx;
	height: 80rpx;
	border: 8rpx solid #F3F3F3;
	border-top: 8rpx solid #FF6B35;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 20rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #666666;
}

/* 空状态样式 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 50rpx 0;
}

.empty-illustration {
	width: 400rpx;
	height: 400rpx;
	margin-bottom: 20rpx;
}

.empty-illustration .img {
	width: 100%;
	height: 100%;
	object-fit: contain;
}

.empty-text {
	font-size: 28rpx;
	color: #999999;
	margin-bottom: 20rpx;
	margin-top: -200rpx;
}

.empty-actions {
	display: flex;
	gap: 15rpx;
}

.action-btn {
	padding: 10rpx 20rpx;
	border-radius: 20rpx;
	border: 1rpx solid var(--u-primary);
	background-color: var(--u-primary);
	color: #FFFFFF;
	cursor: pointer;
	transition: all 0.3s ease;
}

.action-btn:active {
	background-color: var(--u-primary);
}

.btn-text {
	font-size: 24rpx;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}
</style>


